package com.redhipps.hips.client.command;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.redhipps.hips.client.io.IOService;
import com.redhipps.hips.client.io.WriterCallback;
import com.redhipps.hips.client.model.Doctor;
import com.redhipps.hips.client.widget.Dialogs;

public class CreateDoctorCommand extends HipsCommand<Doctor> {

  @Override
  public void execute(final AsyncCallback<Doctor> callback) {
    final WriterCallback<Doctor> writeCallback = new WriterCallback<Doctor>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create doctor failed", caught);
        callback.onFailure(caught);
      }
      public void onSuccess(List<Doctor> result) {
        GWT.log("Create doctor successful", null);
        callback.onSuccess(result.get(0));
      }
    };
    final AsyncCallback<String> dialogCallback = new AsyncCallback<String>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create doctor failed", caught);
      }
      public void onSuccess(String result) {
        if (result == null || result.length() == 0) {
          callback.onSuccess(null);
          return;
        }
        try {
          String[] a = result.split(",");
          Doctor model = new Doctor();
          model.setName(a[0].trim());
//          model.setLogin(a[1].trim());
          createDoctor(model, writeCallback);
        } catch (Exception e) {
          writeCallback.onFailure(e);
        }
      }
    };
    Dialogs.answer("New Doctor", "Specify {name, login}", dialogCallback);
  }

  public void createDoctor(Doctor model, WriterCallback<Doctor> callback)
      throws RequestException {
    IOService io = ioService();
    io.create(context(), model, callback);
  }

}
